package com.tanchengjin.admin.controller;

import com.github.pagehelper.PageHelper;
import com.tanchengjin.admin.model.dao.AdminRoleMapper;
import com.tanchengjin.admin.model.dao.AdminUserMapper;
import com.tanchengjin.admin.model.dao.AdminUserRoleMapper;
import com.tanchengjin.admin.model.pojo.AdminRole;
import com.tanchengjin.admin.model.pojo.AdminUser;
import com.tanchengjin.admin.model.pojo.AdminUserRole;
import com.tanchengjin.admin.service.AdministratorService;
import com.tanchengjin.admin.utils.LayuiAdminServerResponse;
import com.tanchengjin.admin.utils.ServerResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("${app.admin.prefix}/administrators/user")
public class AdminUserManagerController {
    private final static Logger logger = LoggerFactory.getLogger(AdminUserManagerController.class);
    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private AdminUserRoleMapper adminUserRoleMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AdministratorService administratorService;

    @GetMapping("/index")
    public String index() {
        return "/admin/administrators/admin/list";
    }

    @RequestMapping(value = "/list", method = {RequestMethod.GET})
    @ResponseBody
    public LayuiAdminServerResponse index(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "10") int limit) {
        PageHelper.startPage(page, limit);
        List<AdminUser> adminUserList = adminUserMapper.getAll();
        int count = adminUserMapper.count();
        for (AdminUser user : adminUserList) {
            List<AdminUserRole> adminUserRoleList = adminUserRoleMapper.selectByAdminUserId(user.getId());
            List<String> roles = new ArrayList<String>();
            for (AdminUserRole userRole : adminUserRoleList) {
                AdminRole adminRole = adminRoleMapper.selectByPrimaryKey(userRole.getAdminRoleId());
                roles.add(adminRole.getName());
            }
            user.setRole_list(roles);
        }
        return LayuiAdminServerResponse.responseWithSuccess(adminUserList, String.valueOf(count));
    }

    @RequestMapping(value = "/create", method = {RequestMethod.GET})
    public String create(Model model) {
        List<AdminRole> roleList = adminRoleMapper.getAll();
        model.addAttribute("roleList", roleList);
        return "/admin/administrators/admin/add";
    }

    @RequestMapping(value = "", method = {RequestMethod.POST})
    @ResponseBody
    @Transactional
    public ServerResponse store(AdminUser adminUser) {
        int[] roles = adminUser.getRoleIds();
        int i = administratorService.createAdminUser(adminUser, roles);
        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailureMessage("创建失败请重试");
        }
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    @ResponseBody
    public ServerResponse<AdminUser> show(@PathVariable int id) {
        AdminUser adminUser = adminUserMapper.selectByPrimaryKey(id);
        return ServerResponse.responseWithSuccess(adminUser);
    }

    @RequestMapping(value = "/{id}/edit", method = {RequestMethod.GET})
    public String edit(Model view, @PathVariable(value = "id") int id) {
        AdminUser adminUser = adminUserMapper.selectByPrimaryKey(id);
        view.addAttribute("adminUser", adminUser);
        List<AdminRole> roleList = adminRoleMapper.getAll();
        view.addAttribute("roleList", roleList);
        //获取当前用户角色
        List<AdminUserRole> adminUserRoleList = adminUserRoleMapper.selectByAdminUserId(id);
        if (adminUserRoleList != null) {
            List<Integer> userRoleList = new ArrayList<Integer>();
            adminUserRoleList.forEach(e -> {
                userRoleList.add(e.getAdminRoleId());
            });
            view.addAttribute("userRoleList", userRoleList);
        }
        return "/admin/administrators/admin/edit";
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.PUT})
    @ResponseBody
    public ServerResponse update(AdminUser adminUser, @PathVariable("id") int id) {
        AdminUser adminUserInDB = adminUserMapper.selectByPrimaryKey(id);
        if (adminUserInDB == null) {
            return ServerResponse.responseWithFailureMessage("用户不存在，请重试");
        }

        adminUser.setId(id);

        //判断密码是否被传递
        if (adminUser.getPassword() != null && !adminUser.getPassword().isEmpty()) {
            adminUser.setPassword(passwordEncoder.encode(adminUser.getPassword()));
        }

        int i = adminUserMapper.updateByPrimaryKeySelective(adminUser);

        //更新用户角色
        if (adminUser.getRoleIds() != null) {
            administratorService.createAdminUserRole(adminUser.getRoleIds(), adminUser.getId());
        }
        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailureMessage("更新失败，请重试");
        }
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseBody
    public ServerResponse destroy(@PathVariable(value = "id") int id) {
        if (id == 1) {
            return ServerResponse.responseWithFailureMessage("该系统管理员无法被删除!");
        }
        int i = adminUserMapper.deleteByPrimaryKey(id);
        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailureMessage("删除失败请重试");
        }
    }

    @RequestMapping(value = "/batchDelete", method = {RequestMethod.DELETE})
    @ResponseBody
    public ServerResponse batchDelete(@RequestParam(value = "ids[]") int[] ids) {
        int i = administratorService.batchDelete(ids);
        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailureMessage("删除失败请重试");
        }
    }
}
